package com.andy.common.extend

import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.andy.common.listener.RecyclerviewListener

/**
 * Author:Andy
 * Date:2023/4/3 16:50
 * Description:RecyclerViewExt
 */
fun RecyclerView.setListener(listener: RecyclerviewListener) {
    addOnScrollListener(object : RecyclerView.OnScrollListener() {
        var lastVisibleItem: Int = 0
        val swipeRefreshLayout = this@setListener.parent

        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
            lastVisibleItem = (recyclerView.layoutManager as LinearLayoutManager).findLastVisibleItemPosition()
        }

        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            super.onScrollStateChanged(recyclerView, newState)
            if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == recyclerView.adapter?.itemCount) {
                //下拉刷新的时候不可以加载更多
                if (swipeRefreshLayout is SwipeRefreshLayout) {
                    if (!swipeRefreshLayout.isRefreshing) {
                        listener.loadMore()
                    }
                } else {
                    listener.loadMore()
                }
            }
        }

    })

    val swipeRefreshLayout = this.parent
    if (swipeRefreshLayout is SwipeRefreshLayout) {
        swipeRefreshLayout.setOnRefreshListener {
            listener.refresh()
        }
    }
}